package com.wenhai.liuyubobobo.imooc.sort;

import static com.wenhai.liuyubobobo.imooc.sort.HeapSort.swap;

/**
 * 冒泡排序
 *
 * @author wenhai
 * @date   2021/3/12
 */
public class BubbleSort<E extends Comparable<E>> {
    private BubbleSort() {

    }

    public static <E extends Comparable<E>> void sort(E[] data) {
        for (int i = 0; i < data.length; i++) {
            boolean isSwap = false;
            for (int j = 0; j < data.length - 1 - i; j++) {
                if (data[j].compareTo(data[j + 1]) > 0) {
                    swap(data, j, j + 1);
                    isSwap = true;
                }
            }
            if (!isSwap) {
                break;
            }
        }
    }
    public static <E extends Comparable<E>> void sort2(E[] data) {
        for (int i = 0; i < data.length; ) {
            int maxSwapIndex = 0;
            for (int j = 0; j < data.length - 1 - i; j++) {
                if (data[j].compareTo(data[j + 1]) > 0) {
                    swap(data, j, j + 1);
                    maxSwapIndex = j + 1;
                }
            }
            i = data.length - maxSwapIndex;
        }
    }

}
